package ecomm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ecomm.entity.Vehicle;
import ecomm.service.VehicleService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/vehicle")
@RequiredArgsConstructor
public class VehicleController {

    private final VehicleService vehicleService;

    @PostMapping
    public Boolean save(@RequestBody Vehicle v) {
        v.setUpdateTime(LocalDateTime.now());
        return vehicleService.save(v);
    }

    @DeleteMapping("/{id}")
    public Boolean remove(@PathVariable Long id) {
        return vehicleService.removeById(id);
    }

    @PutMapping
    public Boolean update(@RequestBody Vehicle v) {
        v.setUpdateTime(LocalDateTime.now());
        return vehicleService.updateById(v);
    }

    @GetMapping("/{id}")
    public Vehicle get(@PathVariable Long id) {
        return vehicleService.getById(id);
    }

    @GetMapping("/list")
    public Page<Vehicle> list(@RequestParam(defaultValue = "1") int current,
                              @RequestParam(defaultValue = "10") int size,
                              @RequestParam(required = false) String vin) {
        LambdaQueryWrapper<Vehicle> qw = new LambdaQueryWrapper<>();
        qw.like(vin != null, Vehicle::getVin, vin)
                .orderByDesc(Vehicle::getUpdateTime);
        return vehicleService.page(new Page<>(current, size), qw);
    }

    @DeleteMapping("/batch")
    public Boolean batchRemove(@RequestBody List<Long> ids) {
        return vehicleService.removeByIds(ids);
    }
}